
layui.use(['element','table','form','layer'], function(){
    var table = layui.table,
        form = layui.form,
        $ = layui.jquery,
        layer = layui.layer;

    var issueDevice = xmSelect.render({
        el: '#issueDevice',
        toolbar: {show: true},
        name: 'issueDevice',
        layVerify: 'required',
        layVerType: '请选择下发设备',
        data: []
    });

    addWorker = function () {
        $("#resource_form")[0].reset();
        $("#upload_form").attr("disabled", false);
        $("#upload_form").attr("class", "layui-btn");
        $('#id').val("");
        $('#userFaceInfo').val('');
        $('#personCode').val("YG"+new Date().format('yyyyMMddHHmmssS'));
        $('#demo1').removeAttr("src");
        layer.open({
            type: 1
            , title: '添加人员'
            , area: ['55%', '90%']
            , content: $('#uploadDiv')
        });
    };
    //加载字典项 参建单位，所属班组，工种
    loadDictList("cdfaceacsUnit","unitId");
    loadDictList2("cdfaceacsTeam","teamIdQuery","teamId");
    loadDictList2("cdfaceacsWorkType","workTypeIdQuery","workTypeId");

    function loadDictList(dictType,eleId) {
        $.get('/faceAcsWorker/getDictItems', {dictType:dictType}, function (result) {
            if(result != null){
                if(result.data != null){
                    var $opt_html = "<option value=''>请选择</option>";
                    $.each(result.data, function (index, item) {
                        $opt_html += "<option value='" + item.dictKey + "'>" + item.dictName + "</option>";
                    });
                    $("#"+eleId).empty().append($opt_html);
                    form.render('select');

                }
            }
        });
    }
    function loadDictList2(dictType,eleId,eleId2) {
        $.get('/faceAcsWorker/getDictItems', {dictType:dictType}, function (result) {
            if(result != null){
                if(result.data != null){
                    var a$opt_html = "<option value=''>全部</option>";
                    var $opt_html = "<option value=''>请选择</option>";
                    $.each(result.data, function (index, item) {
                        a$opt_html += "<option value='" + item.dictKey + "'>" + item.dictName + "</option>";
                        $opt_html += "<option value='" + item.dictKey + "'>" + item.dictName + "</option>";
                    });
                    $("#"+eleId).empty().append(a$opt_html);
                    $("#"+eleId2).empty().append($opt_html);
                    form.render('select');

                }
            }
        });
    }
    // 上传人脸
    $("#uploadBtn").on("click",function(){
        $("#uploadImg").click();
    });
    $("#uploadImg").on("change",function(){
        var filePath = $(this).val();
        if(!filePath || !filePath.isPicture()){
            layer.msg("请上传图片！",{icon:5});
            return false
        }
        var fr = new FileReader();//创建new FileReader()对象
        //判断图片大小
        var filesize = $(this)[0].files[0];
        if(filesize.size>0){
            if(filesize.size > 1024*500){
                layer.msg('请上传小于500K的图片');
                return false;
            }
        }
        fr.onload = function(e) {
            $('#demo1').attr('src', e.target.result);
            $('#userFaceInfo').val(e.target.result);
        }
        var imgObj = this.files[0];//获取图片
        fr.readAsDataURL(imgObj);//将图片读取为DataURL
    });

    table.render({
        elem: '#workerTable'
        ,url:'/faceAcsWorker/list'
        ,title: '工人管理'
        ,where: {name:''}
        ,cols: [[
            {field: 'xh',type:'numbers', title: '序号',}
            ,{type:'checkbox'}
            ,{field:'name', title:'人员姓名',align:'center'}
            ,{field:'personCode', title:'人员编号',align:'center'}
            ,{field:'unit', title:'所属参建单位',align:'center'}
            ,{field:'team', title:'班组',align:'center'}
            ,{field:'workType', title:'工种',align:'center'}
            ,{field:'createTime', title:'创建时间',  sort: true,templet:
                    function(data){
                        return formatTime(data.createTime);
                    }}
            ,{field:'workType', title:'授权人脸设备',align:'center'}
            ,{field:'authTemplate', title:'权限模板',align:'center'}
            ,{field:'authTime', title:'人员授权时间',  sort: true,templet:
                    function(data){
                        return formatTime(data.authTime);
                    }}
            ,{field:'right',title:'操作',toolbar:'#barOperate',align:'center',width:220}
        ]]
        ,page: true
    });

    function formatTime(data){
        return data ? data.replace("T", " "):"";
    }

    table.on('tool(workerTable)',function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'edit':
                $("#update_form").attr("disabled", false);
                $("#update_form").attr("class", "layui-btn");
                $("#resource_form")[0].reset();
                $("#id").val(data.id);
                $("#userName").val(data.name)
                $("#personCode").val(data.personCode);
                $("#unitId").val(data.unitId);
                $("#teamId").val(data.teamId);
                $("#workTypeId").val(data.workTypeId);
                $("#certificateNum").val(data.certificateNum);
                $("#phone").val(data.phone);
                if(data.faceData === null || data.faceData==="" ){
                    $('#demo1').removeAttr("src");
                }else {
                    $('#demo1').attr('src', data.faceData);
                }
                form.render();
                layer.open({
                    type: 1
                    , title: '编辑人员'
                    , area: ['55%', '90%']
                    , content: $('#uploadDiv')
                });
                break;
            case 'delete':
                layer.confirm('确定要删除吗?', {
                }, function(){
                    layer.load();
                    $.get('/faceAcsWorker/delete',{id:data.id},function (res) {
                        layer.msg(res.msg,{
                            time:500,
                            end:function () {
                                table.reload('workerTable');
                                layer.closeAll();
                            }
                        });
                    });
                });
                break;
        }
    });

    form.on('submit(query_device)',function () {
        var name = $("#name").val();
        var teamId = $("#teamIdQuery").val();
        var workTypeId = $("#workTypeIdQuery").val();
        table.reload('workerTable',{
            where: {name:name,teamId:teamId,workTypeId:workTypeId}
            ,page:  {
                curr:1
            }
        });
        return false;
    });
    // 批量删除
    form.on('submit(batchDelete)',function(obj){
        var checkStatus = table.checkStatus('workerTable');
        var	data = checkStatus.data;
        if(data.length === 0){
            layer.tips("请至少选择一条记录!",this);
            return false;
        }
        var idArr = [];
        data.forEach(item=>{
            idArr.push(item.id);
        });
        var rIds = JSON.stringify(idArr);
        var params = JSON.stringify({"rIds":rIds});
        layer.confirm('确定要删除选择的记录么',function(){
            ajaxPost(params,'/faceAcsWorker/deleteAll');
        });
        return false;
    });
    // 批量授权
    var mutiSelectDeviceData = [];
    var selectedIds;
    form.on('submit(batchAuth)',function(obj){
        var checkStatus = table.checkStatus('workerTable');
        var	data = checkStatus.data;
        if(data.length === 0){
            layer.tips("请至少选择一条记录!",this);
            return false;
        }
        var idArr = [];
        data.forEach(item=>{
            idArr.push(item.id);
        });
        var rIds = JSON.stringify(idArr);
        selectedIds = JSON.stringify({"rIds":rIds});
        $.get('/faceAcsWorker/listOptions', {}, function (result) {
            if(result != null && result.status == 200){
                mutiSelectDeviceData = [];
                if(result.data != null){
                    var deviceList = result.data.deviceList;
                    var authTempalteList = result.data.authTempalteList;
                    $.each(deviceList, function (index, item) {
                        var obj = {name:item.deviceName,value:item.id,selected:false};
                        mutiSelectDeviceData.push(obj);
                    });
                    issueDevice.update({
                        data: mutiSelectDeviceData,
                        autoRow: true,
                    });
                    var $opt_html = "<option value=''>请选择</option>";
                    $.each(authTempalteList, function (index, item) {
                        $opt_html += "<option value='" + item.id + "'>" + item.name + "</option>";
                    });
                    $("#authTemplateId").empty().append($opt_html);
                    form.render('select');
                }
            }
        });
        $("#batchAuthForm")[0].reset();
        layer.open({
            type: 1
            , title: '批量授权'
            , area: ['55%', '70%']
            , content: $('#batchAuthDiv')
        });
        return false;
    });
    // 取消授权
    form.on('submit(cancelBatchAuth)',function(obj){
        var checkStatus = table.checkStatus('workerTable');
        var	data = checkStatus.data;
        if(data.length === 0){
            layer.tips("请至少选择一条记录!",this);
            return false;
        }
        var idArr = [];
        data.forEach(item=>{
            idArr.push(item.id)
        });
        var rIds = JSON.stringify(idArr);
        var params = JSON.stringify({"rIds":rIds});
        layer.confirm('确定要取消授权么',function(){
            ajaxPost(params,'/faceAcsWorker/cancelBatchAuth');
        });
        return false;
    });

    function ajaxPost(params,url){
        $.ajax({
            url: url,
            type: 'post',
            data: {
                params: params
            },
            success: function (res) {
                layer.msg(res.msg,{
                    time:500,
                    end:function () {
                        table.reload('workerTable');
                        layer.closeAll();
                    }
                });
            },
            error: function () {
                layer.closeAll();
                layer.msg("亲,服务器内部错误,请稍后重试!", {icon:5});
            }
        });
    }

    form.on('submit(upload_form)',function(data){
        $("#upload_form").attr("disabled", true);
        $("#upload_form").attr("class", "layui-btn layui-btn-disabled");
        data.field.unit = $("#unitId").find("option:selected").text();
        data.field.team = $("#teamId").find("option:selected").text();
        data.field.workType = $("#workTypeId").find("option:selected").text();
        layer.load();
        $.ajax({
            type: 'post',
            url: '/faceAcsWorker/saveOrUpdate',
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(data.field),
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function (){
                    layer.closeAll();
                },1000);
                $("#upload_form").attr("disabled", false);
                $("#upload_form").attr("class", "layui-btn");
                table.reload('workerTable');
            },
        });
        return false;
    });

    $("#cancel_form").on('click',function (){
        layer.closeAll();
        return false;
    });
    form.on('submit(confirmAuthForm)',function(data){
        $("#confirmAuthForm").attr("disabled", true);
        $("#confirmAuthForm").attr("class", "layui-btn layui-btn-disabled");
        data.field.authTemplate = $("#authTemplateId").find("option:selected").text();
        data.field.params = selectedIds;
        var deviceList = issueDevice.getValue();
        var temArr = [];
        for(var i in deviceList){
            var obj = {"id":deviceList[i].value,"name":deviceList[i].name};
            temArr.push(obj);
        }
        data.field.issueDevices = JSON.stringify(temArr);
        layer.load();
        $.ajax({
            type: 'post',
            url: '/faceAcsWorker/batchAuth',
            data: data.field,
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function (){
                    layer.closeAll();
                },1000);
                $("#confirmAuthForm").attr("disabled", false);
                $("#confirmAuthForm").attr("class", "layui-btn");
                table.reload('workerTable');
            },
        });
        return false;
    });
    $("#cancelAuthForm").on('click',function (){
        layer.closeAll();
        return false;
    });

});

function parseStatus(status) {
    if(typeof status == "undefined" || status == null){
        return "未知";
    }
    switch (Number(status)) {
        case 0 : return "在线";
        case 1 : return "离线";
        default: return "未知";
    }
}
function reload(){
    location.reload();
}
String.prototype.isPicture = function(){
    //判断是否是图片 - strFilter必须是小写列举
    var strFilter=".jpeg|.gif|.jpg|.png|.bmp|.pic|.svg|"
    if(this.indexOf(".")>-1)
    {
        var p = this.lastIndexOf(".");
        var strPostfix=this.substring(p,this.length) + '|';
        strPostfix = strPostfix.toLowerCase();
        if(strFilter.indexOf(strPostfix)>-1)
        {
            return true;
        }
    }
    return false;
}
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}